
package com.be.beadmin.design.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaQueryBuilderNew;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.design.dto.input.StandProductProcessInfoDto;
import com.be.beadmin.design.dto.input.StandProductProcessInfoPageDto;
import com.be.beadmin.design.dto.output.StandProductProcessInfoEx;
import com.be.beadmin.design.dto.output.StandProductProcessInfoExcelEx;
import com.be.beadmin.design.dto.output.UnStandProductWorkHourAndCycleEx;
import com.be.beadmin.design.entity.*;
import com.be.beadmin.design.entity.Process;
import com.be.beadmin.design.mapper.StandProductMapper;
import com.be.beadmin.design.mapper.StandProductProcessInfoMapper;
import com.be.beadmin.design.mapper.StandProductProcessInfoMapperEx;
import com.be.beadmin.design.repository.StandProductProcessInfoRepository;
import com.be.beadmin.design.repository.StandProductRepository;
import com.be.beadmin.design.service.StandProductProcessInfoService;
import com.be.beadmin.design.util.ExcelListener;
import com.be.beadmin.project.entity.BatchProduct;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @description 服务实现
* @author ljh
* @date 2023-06-13
**/
@Service
@RequiredArgsConstructor
public class StandProductProcessInfoServiceImpl implements StandProductProcessInfoService {

    @Autowired
    private  StandProductProcessInfoRepository standProductProcessInfoRepository;
    @Autowired
    private  StandProductProcessInfoMapper standProductProcessInfoMapper;
    @Autowired
    private  StandProductProcessInfoMapperEx standProductProcessInfoExMapper;

    @Autowired
    private StandProductRepository standProductRepository;
    @Autowired
    private StandProductMapper standProductMapper;


    @Override
    public Page<StandProductProcessInfoEx> getStandProductProcessInfoByStandTypeIdAndPage(StandProductProcessInfoPageDto standProductProcessInfoPageDto) {
        PageEntity pageEntity = standProductProcessInfoPageDto.getPageEntity();
        String standTypeId = standProductProcessInfoPageDto.getStandTypeId();
        if(standTypeId==null) throw new BeadminException("没有标准柜体编号");
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() -1,
                pageEntity.getPageSize());
        Page<StandProductProcessInfo> page = standProductProcessInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(StandProductProcessInfo_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate pre3 = criteriaBuilder.equal(root.get(StandProductProcessInfo_.standTypeId), standTypeId); //过滤为0
                    list.add(pre3);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(StandProductProcessInfo_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<StandProductProcessInfoEx> page1 = page.map(standProductProcessInfoExMapper::toEntity);
        return page1;
    }

    @Override
    public Page<StandProductProcessInfoEx> getStandProductProcessInfoByPage(PageEntity pageEntity) {
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() -1,
                pageEntity.getPageSize());
        Page<StandProductProcessInfo> page = standProductProcessInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(StandProductProcessInfo_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(StandProductProcessInfo_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<StandProductProcessInfoEx> page1 = page.map(standProductProcessInfoExMapper::toEntity);
        return page1;
    }

    @Override
    public List<StandProductProcessInfoExcelEx> getStandProductProcessInfoByStandTypeIds(List<String> standTypeIds) {
        List<StandProductProcessInfo> standProductProcessInfoList= standProductProcessInfoRepository.findStandProductProcessInfoByStandTypeIdInAndDelete(standTypeIds, 0);

        List<StandProductProcessInfoExcelEx> resultEx = standProductProcessInfoList.stream().map(standProductProcessInfo -> {
            StandProductProcessInfoExcelEx standProductProcessInfoExcelEx = new StandProductProcessInfoExcelEx();
            BeanUtils.copyProperties(standProductProcessInfo, standProductProcessInfoExcelEx);
            return standProductProcessInfoExcelEx;
        }).collect(Collectors.toList());

        return resultEx;
    }

    @Override
    public void addStandProductProcessInfo(StandProductProcessInfoDto standProductProcessInfoDto) {
            StandProductProcessInfo result = standProductProcessInfoRepository.findStandProductProcessInfoByIdAndDelete(standProductProcessInfoDto.getId(), 0);
            if(ObjectUtil.isNotEmpty(result)) {
                throw new BeadminException("StandProductProcessInfo不存在,请重新查询");
            }
            StandProductProcessInfo standProductProcessInfo = standProductProcessInfoMapper.toEntity(standProductProcessInfoDto);
            standProductProcessInfoRepository.save(standProductProcessInfo);
    }

    /**
     * @param standProduct
     * @param process
     */
    @Override
    public StandProductProcessInfo getStandProductProcessInfoByStandProductAndProcess(StandProduct standProduct, Process process) {
        StandProductProcessInfo standProductProcessInfo = standProductProcessInfoRepository.findStandProductProcessInfoByStandTypeIdAndProcessIdAndDelete(standProduct.getId(), process.getId(), 0);
        return standProductProcessInfo;
    }

    @Override
    public void updateStandProductProcessInfo(StandProductProcessInfoDto standProductProcessInfoDto) {
        StandProductProcessInfo standProductProcessInfo = standProductProcessInfoMapper.toEntity(standProductProcessInfoDto);
        standProductProcessInfoRepository.save(standProductProcessInfo);

        List<StandProductProcessInfo> standProductProcessInfoList = standProductProcessInfoRepository.findStandProductProcessInfoByStandTypeIdAndIsProductionProcessAndDelete(standProductProcessInfoDto.getStandTypeId(),1,0);
        float sum = 0 ;
        for(StandProductProcessInfo standProductProcessInfo1:standProductProcessInfoList){
            sum += standProductProcessInfo1.getStandWorkHour();
        }
        StandProduct standProduct =  standProductRepository.findStandProductById(standProductProcessInfoDto.getStandTypeId());
        standProduct.setStandManufactWorkHour(sum);
        standProductRepository.save(standProduct);
    }


    @Override
    public void delStandProductProcessInfo(String id) {
        StandProductProcessInfo standProductProcessInfo = standProductProcessInfoRepository.findStandProductProcessInfoById(id);
        standProductProcessInfo.setDelete(1);
        standProductProcessInfoRepository.save(standProductProcessInfo);
    }

    @Override
    public void delStandProductProcessInfos (List<String> ids) { }


    @Override
    public void uploadStandProductProcessInfo(MultipartFile file) {

        ExcelListener<StandProductProcessInfoExcelEx> excelListener = new ExcelListener<>();
        try{
            ExcelReader excelReader = EasyExcelFactory.read(file.getInputStream(),StandProductProcessInfoExcelEx.class ,excelListener).headRowNumber(1).build();
            excelReader.readAll();
            excelReader.finish();
        }catch (ExcelDataConvertException e){
            throw new BeadminException("表中数据类型有误");
        }catch (Exception e) {
            throw new BeadminException("解析失败");
        }

        List<StandProductProcessInfoExcelEx> dataList = excelListener.getDatas();
        for (StandProductProcessInfoExcelEx item : dataList){
            StandProductProcessInfo process = standProductProcessInfoRepository.findStandProductProcessInfoByStandTypeCodeAndProcessCode(item.getStandTypeCode(), item.getProcessCode());
            process.setIsProductionProcess(item.getIsProductionProcess());
            process.setStandWorkHour(item.getStandWorkHour());
            process.setStandCycle(item.getStandCycle());
            standProductProcessInfoRepository.save(process);
        }

    }

}